<?php
namespace app\admin\controller;

use app\common\model\Style as StyleModel;
use app\admin\tool\Parser;
use think\Request;
use think\Loader;
/**
 * 风格
 * Class Style
 * @package app\admin\controller
 */
class Style extends Base{

    public function index(){
        $where = [];
        $model = StyleModel::where($where)->order('id desc')->paginate(10);

        $parser = new Parser();

        $this->data['title'] = '风格列表';
        $this->data['model'] = $model;
        $this->data['column'] = $this->column();
        $this->data['parser'] = $parser;

        return view('',$this->data);
    }


    public function add(){

        $this->data['title'] = '添加风格';
        return view('',$this->data);
    }


    /**
     * @param Request $request
     * @return \think\response\View
     * @throws
     */
    public function edit(Request $request){
        $id = $request->param('id');

        $model = StyleModel::get($id);
        $model->image_list = json_decode($model->image_list);

        $this->data['model'] = $model;
        $this->data['title'] = '风格编辑';

        return view('',$this->data);
    }


    public function handle(Request $request){
        $data = $request->post();
        $validate = Loader::validate('Style');
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $data['image_list'] = json_encode($data['image_list']);

        $data['op_user'] = $this->admin->id;
        if(empty($data['id'])){
            $data['add_time'] = $data['update_time'] = time();
            $model = new StyleModel();
            $model->data($data);
            if($model->allowField(true)->save()){
                $this->success("新增成功");
            }
        }else{
            $data['update_time'] = time();
            $model = new StyleModel();
            if($model ->allowField(true)->save($data,['id'=>$data['id']])){
                $this->success("更新成功");
            }
        }

        $this->error("操作失败");
    }


    public function delete(Request $request){
        $id = $request->param('id');
        $model = StyleModel::get($id);

        //查看已经报名的活动

        $res = $model->delete();
        if($res){
            $this->success('删除成功');
        }
        $this->error("删除失败");
    }



    protected function column(){
        return [
            'title'=>['name'=>'风格名称','fun'=>'text','options'=>''],
            'cover'=>['name'=>'风格缩略图','fun'=>'singleImage','options'=>['style'=>'width:50px;height:50px']],
        ];
    }

}